package com.xm.security.exception;

import com.alibaba.fastjson.JSON;
import com.xm.common.entity.R;
import com.xm.common.entity.ResConst;
import com.xm.common.utils.StrPool;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义异常处理
 *
 * @author yousj
 * @since 2021/6/12
 */
public interface ExceptionAdviceHandler {

    @SneakyThrows
    default void accessDeniedHandler(Exception e, HttpServletResponse res){
        r(res, R.isFail(ResConst.FORBIDDEN_ERROR));
    }

    @SneakyThrows
    default void authenticationEntryPointHandler(Exception e, HttpServletResponse res){
        r(res, R.isFail(ResConst.UNAUTHORIZED_ERROR));
    }

    @SneakyThrows
    default void handler(Exception e, HttpServletResponse res){
        r(res, R.isFail(ResConst.SYSTEM_ERROR));
    }

    default void r(HttpServletResponse res, R r) throws IOException {
        res.setCharacterEncoding(StrPool.UTF_8);
        res.setStatus(HttpStatus.OK.value());
        res.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter writer = res.getWriter();
        writer.write(JSON.toJSONString(r));
        writer.flush();
        writer.close();
    }

}
